'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: embeddings_service.py
* @Time: 2025/11/12
* @All Rights Reserve By Brtc
'''
from dataclasses import dataclass
from tkinter.font import names

import tiktoken
from injector import inject
from langchain.embeddings import CacheBackedEmbeddings
from langchain_community.storage import RedisStore
from langchain_core.embeddings import Embeddings
from langchain_openai import OpenAIEmbeddings
from redis import Redis
LLMOPS_COLLECTION_NAME = 'llmops-ai-openai-collection'

@inject
@dataclass
class EmbeddingsService:
    """文本嵌入模型"""
    _store:RedisStore
    _embeddings:Embeddings
    _cache_backend_embeddings:CacheBackedEmbeddings

    def __init__(self, redis:Redis):
        """构造函数，初始化文本嵌入模型客户端、存储器、缓存客户端"""
        self._store = RedisStore(client=redis)
        self._embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
        self._cache_backend_embeddings = CacheBackedEmbeddings.from_bytes_store(
            self._embeddings,
            self._store,
            namespace=LLMOPS_COLLECTION_NAME,
        )
    @classmethod
    def calculate_token_count(cls, query:str)->int:
        """计算传入的文本的token数量"""
        encoding = tiktoken.encoding_for_model("gpt-3.5")
        return len(encoding.encode(query))

    @property
    def store(self)->RedisStore:
        return self._store

    @property
    def embeddings(self)->Embeddings:
        return self._embeddings

    @property
    def cache_backed_embeddings(self)->CacheBackedEmbeddings:
        return self._cache_backend_embeddings
